package com.lenovo.dll.nebula.vod.parse.service;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.lenovo.dll.nebula.vod.parse.Constant;
import com.lenovo.dll.nebula.vod.parse.service.IPostService;

public class PostService implements IPostService {
	InputStream in = null;
	HttpURLConnection urlConn = null;
	
	
	@Override
	public InputStream doPost(Map<String, String> params, String strUrl) 
		throws IOException {
		try {
			String strParams = appendParameters(params);
			URL url = new URL(strUrl);
			urlConn = (HttpURLConnection) url.openConnection();
			urlConn.setRequestMethod("POST");
			urlConn.setConnectTimeout(Constant.TIMEOUT_CONNECTION);
			urlConn.setReadTimeout(Constant.TIMEOUT_READ);
			urlConn.setDoInput(true);
			urlConn.setDoOutput(true);
			byte[] b = strParams.getBytes();
			urlConn.getOutputStream().write(b, 0, b.length);
			urlConn.getOutputStream().flush();
			urlConn.getOutputStream().close();
			int responseCode = urlConn.getResponseCode();
			System.out.println("responseCode:"+responseCode);
			Log.i(Constant.LOG_TAG_VOD_SEARCH, "response code when doing post:"
					+ responseCode);
			in = urlConn.getInputStream();
		}finally{
		}
		return in;
	}
	
	
	@Override
	public void releaseConnection() throws IOException {
		if(in != null){
			in.close();
		}
		if(urlConn != null){
			urlConn.disconnect();
		}
	}

	
	@SuppressWarnings("rawtypes")
	private String appendParameters(Map<String, String> parameters) {
		StringBuffer params = new StringBuffer();
		for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
			Entry element = (Entry) iter.next();
			params.append(element.getKey().toString());
			params.append("=");
			try {
				params.append(URLEncoder.encode(element.getValue().toString(),
						"UTF-8"));
			} catch (UnsupportedEncodingException uee) {
				Log.e(Constant.LOG_TAG_VOD_SEARCH,
						"UnsupportedEncodingException when appending post parameters",
						uee);
			}
			params.append("&");
		}

		if (params.length() > 0) {
			params.deleteCharAt(params.length() - 1);
		}
		return params.toString();
	}
}
